import sys
import pygame
from settings import Settings
from star import Star


class StarsImage:
    """管理游戏资源和行为的类"""
    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.settings = Settings()
        self.screen = pygame.display.set_mode \
            ((self.settings.screen_width, self.settings.screen_height))

        pygame.display.set_caption("Stars Image")
        self.star = Star(self)
        self.stars = pygame.sprite.Group()

        self._create_fleet()

    def _create_fleet(self):
        """创建一个星星阵列"""
        # 星星的横向间距为星星的宽度
        # 星星的纵向间距为星星的高度
        star = Star(self)
        # alien.rect.size 是一个元组，包含外星人的宽度和高度
        star_width, star_height = star.rect.size

        current_x = star_width
        current_y = star_height

        while current_y < (self.settings.screen_height - 3 * star_height):
            while current_x < (self.settings.screen_width - 2 * star_width):
                self._create_star(current_x, current_y)
                current_x += 2 * star_width

            # 添加一行外星人后，重置x值并递增y值
            current_x = star_width
            current_y += 2 * star_height

    def _create_star(self, x_position, y_position):
        """创建一个星星并将其放在当前行中"""
        # current_x表示我们要在屏幕上方值得下一个外星人的水平位置
        new_star = Star(self)
        new_star.x = x_position
        new_star.rect.x = x_position
        new_star.rect.y = y_position
        self.stars.add(new_star)

    def _check_events(self):
        """响应按键和鼠标事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()

    def _update_screen(self):
        """更新屏幕上的图像，并切换到新屏幕"""
        # 每次循环时都会重新绘制屏幕
        self.screen.fill(self.settings.bg_color)
        self.star.blitime()
        self.stars.draw(self.screen)
        pygame.display.flip()

    def run_game(self):
        """开始游戏的主循环"""
        # 设置循环的目的是不断的更新并打印运行窗口
        while True:
            self._check_events()
            self._update_screen()

            self.clock.tick(60)


if __name__ == '__main__':
    st = StarsImage()
    st.run_game()
